package servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import dao.CategoryDao;
import entity.Category;
import entity.Product;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/Category")
public class CategoryService extends BasicServlet{

    //得到分类列表
    public Object categoryList(HttpServletRequest request, HttpServletResponse response){
        List<Category> categoryList = null;
        try {
            categoryList = CategoryDao.getCategoryList();
            request.getSession().setAttribute("categoryList",categoryList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(categoryList, SerializerFeature.WriteDateUseDateFormat);
    }


    //根据分类的ID得到相应的分类商品数据
    public Object categoryProduct(HttpServletRequest request, HttpServletResponse response){
        List<Product> productList = null;
        String categoryId = request.getParameter("categoryId");
        try {
            productList = CategoryDao.getProductListByCategoryId(categoryId);
            request.getSession(false).setAttribute("categoryProduct",productList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(productList,SerializerFeature.WriteDateUseDateFormat);
    }


    //进行分页
    public String categoryDetails(HttpServletRequest request,HttpServletResponse response){
        List<Product> productList = new ArrayList<>();
        int pageIndex = Integer.parseInt(request.getParameter("pageIndex")),categoryId = Integer.parseInt(request.getParameter("categoryId"));
        int length = CategoryDao.getCategoryDataLength(categoryId);
        if(pageIndex <= 0){
            pageIndex = 1;
        }else if(pageIndex >= length){
            pageIndex = length;
        }
        request.getSession(false).setAttribute("dataLength",length);
        request.getSession(false).setAttribute("categoryId",categoryId);
        try {
            productList = CategoryDao.getPageProduct(pageIndex - 1 ,categoryId);
            request.getSession(false).setAttribute("pageProduct",productList);
            request.getSession(false).setAttribute("categoryName",CategoryDao.getCategoryName(categoryId));
            request.getSession(false).setAttribute("currentPage",pageIndex);
            response.sendRedirect("/page/category");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Success";
    }
}
